<template>
    <Transition>
        <div class="contain" v-if="flag">
            <div class="card" style="min-width:900px;">
                <div class="header flex">
                    <div class="goHome flex">
                        <p class="title">入库明细</p>
                    </div>
                    <div class="flex">
                        <button class="submit" @click="printHandle">打印</button>
                        <el-icon size="22" style="margin-right: 37px; cursor: pointer;" @click="close">
                            <Close />
                        </el-icon>
                    </div>
                </div>

                <div class="printMain" id="printMain" ref="print">
                    <div>
                        <h3 class="printTitle">{{ schoolName }}卫材外购入库单</h3>
                    </div>
                    <div class="flex printPage">
                        <p class="signature">NO.{{ form.receiptCode }}</p>
                        <div class="flex Pagination">
                        </div>
                    </div>
                    <div class="flex centerBox">
                        <p>库房：物资库房</p>
                        <p>总金额：{{ allMoney }} 元</p>
                        <!-- <p>第1页/共1页</p> -->
                        <p>供应商：{{ form.supplier }}</p>
                    </div>
                    <div class="table_box">
                        <el-table :data="currentList" border style="width: 100%;font-size: 14px;" class="custom-table"
                            :header-cell-style="{ 'background': '#F6F6FE', 'color': '#5B686D' }" size="small"
                            :cell-style="{ 'color': '#5B686D' }">
                            <el-table-column type="index" label="序号" width="60" />
                            <el-table-column prop="materialName" label="材料信息" min-width="130" />
                            <el-table-column prop="categoriesName" label="材料类别" />
                            <el-table-column prop="specification" label="规格" />
                            <el-table-column prop="unit" label="单位" />
                            <el-table-column prop="quantity" label="入库数量" />
                            <!-- <el-table-column prop="availableQuantity" label="可用数量" /> -->
                            <el-table-column prop="price" label="采购价" />
                            <el-table-column prop="finalSellingPrice" label="采购价金额" min-width="90">
                                <template #default="scope">
                                    <span>{{ (parseFloat(scope.row.quantity) * parseFloat(scope.row.price)).toFixed(5)
                                        }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="售价" />
                            <el-table-column prop="finalSellingPrice" label="售价金额">
                                <template #default="scope">
                                    <span>{{ (parseFloat(scope.row.quantity) * parseFloat(scope.row.price)).toFixed(5)
                                        }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="flex footer">
                            <p>&emsp;摘要</p>
                            <p>&emsp;填制人：{{ form.createdBy.split("(")[0] }}</p>
                            <p>&emsp;填制日期：{{ form.createdAt }}</p>
                        </div>
                    </div>
                </div>

                <div style="margin: 30px 0 0 60px;">
                    <el-pagination :total="total" :page-size="pageSize" :current-page="page"
                        layout="total, prev, pager, next " @size-change="changePageSize"
                        @current-change="changeCurrentPage">
                    </el-pagination>
                </div>
            </div>
            <div style="width: 1px;height: 100px;"></div>
        </div>
    </Transition>
</template>

<script>
import { httpService } from "@/utils/httpService";
import Icon from '@/components/Icon.vue';
import { ArrowLeft, Close } from "@element-plus/icons-vue";
import { ElConfigProvider, ElMessage, ElForm, ElLoading } from "element-plus";
import { getCurrentInstance } from "vue";
import { formatTime } from "@/utils/dateFormat";

export default {
    name: "leftMenu",
    components: { Icon, ArrowLeft, ElMessage, ElForm, ElLoading, Close, ElConfigProvider, },
    data() {
        return {
            flag: false,
            form: {},
            printList: [],
            page: 1,
            pageSize: 10,
            pageSizeAll: 10000,
            total: 0,
            allMoney: 0,

            submitFlag: false,
            currentList: [],
        };
    },
    computed: {
        currentList() {
            return this.printList.slice((this.page - 1) * this.pageSize, this.page * this.pageSize)
        },
    },

    mounted() {
        const instance = getCurrentInstance()
        this.schoolName = instance.appContext.config.globalProperties.$schoolName

    },
    methods: {
        queryById(id) {
            httpService(`/javaApi/stockIn/list/${this.page}/${this.pageSizeAll}`, { receiptId: id }, "get").then(
                (data) => {
                    if (data.list) {
                        data.list.map(item => item.createdAt = formatTime(new Date(item.createdAt)))
                        this.form.requestor = data.list[0].requestor
                        this.printList = data.list
                        this.total = data.total
                        this.allMoney = data.list.reduce((sum, item) => sum + (item.price * item.quantity), 0);
                    }
                }
            );
        },

        changePageSize(size) {
            this.pageSize = size;
            this.queryById(this.form.id);
        },
        changeCurrentPage(page) {
            this.page = page;
            this.queryById(this.form.id);
        },
        close() {
            this.flag = false
            this.form = {}
            this.printList = []
            this.page = 1
            this.pageSize = 50
            this.total = 0

        },


        printHandle() {
            const itemsPerPage = 10; // 每页最多打印的条目数
            const totalPages = Math.ceil(this.printList.length / itemsPerPage); // 总页数

            // 将数据分成每页的组
            const paginatedList = Array.from({ length: totalPages }, (_, i) =>
                this.printList.slice(i * itemsPerPage, (i + 1) * itemsPerPage)
            );

            let totalSum = 0; // 初始化合计为 0

            const printContent = paginatedList.map((pageItems, pageIndex) => {
                const pageSum = pageItems.reduce((sum, item) => {
                    const itemTotal = (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
                    return sum + itemTotal;
                }, 0);
                totalSum += pageSum;
                return `
            <div class="table-container">
                <p class="pTitle">${this.schoolName}卫材外购入库单</p>
                <div class="table-header">
                    <div>NO.Y${this.form.receiptCode}</div>  
                </div>
                <div class="table-info">
                    <span>库房: 物资库房</span>
                    <span>第 ${pageIndex + 1} 页/共 ${totalPages} 页</span>
                    <span>供应商: ${this.form.supplier}</span>  
                </div>
                <table>
                    <thead>
                        <tr>
                            <td>材料信息</td>
                            <td>材料类别</td>
                            <td>规格</td>
                            <td>单位</td>
                            <td>数量</td>
                            <td>采购价</td>
                            <td>采购价金额</td>
                            <td>售价</td>
                            <td>售价金额</td>
                        </tr>
                    </thead>
                    <tbody>
                        ${pageItems.map(item => {
                    const itemTotal = (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
                    return `
                                <tr>
                                    <td>${item.materialName}</td>
                                    <td>${item.categoriesName}</td>
                                    <td>${item.specification}</td>
                                    <td>${item.unit}</td>
                                    <td>${item.quantity}</td>
                                    <td>${parseFloat(item.price).toFixed(5)}</td>
                                    <td>${itemTotal.toFixed(5)}</td>  
                                    <td>${parseFloat(item.price).toFixed(5)}</td>
                                    <td>${itemTotal.toFixed(5)}</td>  
                                </tr>
                            `;
                }).join('')}
                        <tr>
                            <td>本页小计</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>${pageSum.toFixed(5)}</td>
                        </tr>
                        <tr>
                            <td>合&emsp;计</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>${totalSum.toFixed(5)}</td>
                        </tr> 
                    </tbody>
                </table>
                <div class="table-footer">
                    <div>摘要</div>
                    <div>填制人: ${this.form.createdBy.split("(")[0]}</div>
                    <div>填制日期: ${this.form.createdAt}</div> 
                </div>
            </div>
            <div style="page-break-after: always;"></div> <!-- 确保分页 -->
        `;
            }).join('');

            // 创建打印窗口
            const WinPrint = window.open('', '', 'width=800,height=600');
            WinPrint.document.write(`
        <html>
        <head>
            <title>打印</title>
            <style>
                @media print { 
                    @page {
                        margin: 30px 20mm;
                    }
                    body {
                        margin: 0;
                        font-family: Arial, sans-serif;
                    }
                    .table-container {
                        width: 100%;
                        text-align: center;
                        page-break-before: always; /* 强制每个新内容开始时分页 */
                    }
                    .table-container:last-child {
                        page-break-after: auto; /* 最后一页不分页 */
                    }
                    .table-header,
                    .table-info,
                    .table-footer {
                        display: flex;
                        justify-content: space-between; 
                    }
                    .pTitle {
                        font-size: 20px;
                        font-weight: 400;
                        text-align: center;
                    }
                    table {
                        width: 100%;
                        border: 1px solid #000;
                        border-collapse: collapse;
                    }
                    th, td {
                        border: 1px solid #000; 
                        text-align: center;
                    }
                    tr:nth-child(even) {
                        background-color: #f2f2f2; /* 隔行变色 */
                    }
                }
            </style>
        </head>
        <body>
            ${printContent}
        </body>
        </html>
    `);
            WinPrint.document.close();
            WinPrint.print();
            WinPrint.close();
        },




    },
}
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}

.flex {
    display: flex;
    align-items: center;
}

.contain {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.35);
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 99;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    overflow-y: auto;
}

.card {
    width: 70%;
    height: calc(100vh - 100px);
    background-color: #fff;
    border-radius: 13px;
    margin-top: 50px;
    margin-bottom: 50px;
}

.table_box {
    height: calc(100vh - 400px);
    overflow: auto;
}

.header {
    justify-content: space-between;
    height: 65px;
    border-bottom: 1px solid #D6DBE2;
}

.header .title {
    color: #000000;
    font-size: 18px;
    font-weight: bold;
    margin-left: 32px;
}

.submit {
    width: 77px;
    height: 38px;
    background-color: #6F72FF;
    border-radius: 10px;
    border: none;
    margin-right: 32px;
    color: #fff;
    font-size: 15px;
}

.main {
    /* width: 50vw; */
    padding: 23px 60px 0 60px;
    margin: 10px auto 0;
    /* display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    align-content: flex-start; */
    overflow-y: auto;
}

.main_li {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.inputBox {
    width: calc((100% - 90px) / 3);
    /* width: calc((100% - 100px) / 2); */
    margin-bottom: 15px;
}

.inputName {
    color: #5B686D;
    font-size: 15px;
    margin-bottom: 5px;
}

.inputName span {
    color: #FF0000;
    font-size: 15px;
    margin-bottom: 5px;
}

.myInput {
    width: calc(100% - 19px);
    height: 42px;
    border-radius: 10px;
    border: 1px solid #D6DBE2;
    outline: none;
    font-size: 15px;
    color: #000;
    padding-left: 19px;
}

.myInput::placeholder {
    color: #A9B6BB;
}

.myText {
    width: calc(100% - 36px);
    height: 150px;
    border-radius: 10px;
    border: 1px solid #D6DBE2;
    resize: none;
    outline: none;
    padding: 18px;
    font-size: 15px;
    color: #000;
}

.myText::placeholder {
    color: #A9B6BB;
}


input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

/* 对于Firefox */
input[type="number"] {
    -moz-appearance: textfield;
}



.select ::v-deep .el-tooltip__trigger {
    width: 100%;
    height: 44px;
    border-radius: 10px;
}

.el-select-dropdown__item {
    padding-left: 15px;
}

::v-deep .el-select {
    --el-color-primary: #D6DBE2;
}



.v-enter-active,
.v-leave-active {
    transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
    opacity: 0;
}
</style>

<style>
.printMain {
    margin: 10px 60px 0;
}

.printTitle {
    text-align: center;
    margin-bottom: 10px;
    color: #2B2B2B;
    font-size: 17px;
}

.printPage {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.signature {
    color: #2B2B2B;
    font-size: 17px
}

.Pagination {
    color: #2B2B2B;
    font-size: 17px;
    display: flex;
    align-items: center;
}

.nextBtn {
    color: #6F72FF;
    margin-left: 30px;
}

.centerBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}

.footer {
    color: #959EA1;
    font-size: 15px;
    margin-top: 10px;
    display: flex !important;
    align-items: center !important;
    justify-content: space-between;
}

.p1 {
    /* width: calc(100% / 7); */
}

.p2 {
    /* width: calc((100% / 7) * 2); */
    white-space: nowrap;
}


.applyBtn {
    width: 100px;
    line-height: 35px;
    border-radius: 10px;
    font-size: 15px;
    background-color: #6F72FF;
    color: #fff;
    text-align: center;
    cursor: pointer;
}
</style>